package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ")
    public void processOutTimeOrder() {

        log.info("定时处理支付超时订单 {}", LocalDateTime.now());

        // 当前订单时间 - 15 > 下订单的时间  >: 超时
        //获取超时的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> outTimeOrders = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        if(outTimeOrders != null && !outTimeOrders.isEmpty()){
            for (Orders outTimeOrder : outTimeOrders) {
                //修改超时订单的状态和一些字段的内容
                outTimeOrder.setStatus(Orders.CANCELLED);
                outTimeOrder.setCancelReason("订单超时自动取消");
                outTimeOrder.setOrderTime(LocalDateTime.now());
                orderMapper.update(outTimeOrder);
            }
        }
    }


    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨1点处理 一直处理派送中的订单
    public void  processDeliveryOrder(){
        log.info("定时处理隔天在派送中的订单");
        //获得前一天 在派送中的订单
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> deliveryOrders = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if(deliveryOrders != null && !deliveryOrders.isEmpty()){
            for (Orders deliveryOrder : deliveryOrders) {
                //修改派送订单的状态
                deliveryOrder.setStatus(Orders.COMPLETED);
                orderMapper.update(deliveryOrder);
            }
        }
    }














}
